import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../model/community_video_model.dart';
import '../model/video_item_model.dart';

class CommunityController extends GetxController {

  final ScrollController scrollController = ScrollController();
  final List<VideoItemModel> videoList = [];
  bool isLoadingMore = false;
  bool isLoadingData = true;
  bool hasMore = true;
  var _url = "https://baobab.kaiyanapp.com/api/v2/feed";

  @override
  void onInit() {
    super.onInit();

    scrollController.addListener(() {
      if (scrollController.position.pixels == scrollController.position.maxScrollExtent && !isLoadingMore) {
        _loadMore();
      }
    });

    loadData();
  }

  @override
  void onClose() {
    scrollController.dispose();
    super.onClose();
  }

  Future<void> _loadMore() async {
    isLoadingMore = true;
    update();
    await loadData();
  }

  Future loadData() async {
    Dio dio = Dio();
    final response = await dio.get(_url);
    var model = CommunityVideoModel.fromJson(response.data);
    var dataList = model.issueList![0].itemList ?? [];
    if (dataList.isNotEmpty) {
      dataList = dataList.where((x)=> x.type == "video").toList();
      videoList.addAll(dataList);
    } else {
      hasMore = false;
    }
    _url = model.nextPageUrl ?? '';
    isLoadingMore = false;
    isLoadingData = false;
    update();
  }
}
